package com.cyt.sys.util;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.SMSPayload;
import com.cyt.base.util.DictCode;
import com.cyt.sys.util.cache.ParamConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 短信平台调用接口工具类（极光）
 *
 * Created by dingxu on 2019/12/30.
 *
 */
public class SMSUtils {

    private static Logger logger = LoggerFactory.getLogger(SMSUtils.class);

    public  static String sendVerifyCodeByApply(SMSDto smsDto){
        String masterSecret="";
        String appKey="";
        if(smsDto.getType().equals(DictCode.SYS_SMS_PLATFORM)){
            masterSecret= ParamConfigUtils.getParamConfig("smsMasterSecret").getInfo();
            appKey=ParamConfigUtils.getParamConfig("smsAppKey").getInfo();
        }else{
            masterSecret = smsDto.getSmsMasterSecret();
            appKey = smsDto.getSmsAppKey();
        }
        SMSClient client = new SMSClient(masterSecret, appKey);
        SMSPayload payload = SMSPayload.newBuilder()
                .setMobileNumber(smsDto.getMobile())
                .setTempId(Integer.parseInt(smsDto.getTemp_id()))
                .setTempPara(smsDto.getTemp_para())
                .build();
        String result = null;
        try {
            SendSMSResult res = client.sendTemplateSMS(payload);
            result = res.toString();
            logger.info(result);
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later.", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status:" + e.getStatus());
            logger.info("Error Message:" + e.getMessage());
        } catch (Exception e) {
            logger.error(">>>>>e:" + e);
            e.printStackTrace();
        }
        if (result.indexOf("msg_id") != -1) {
            return result;
        } else {
            return "";
        }
    }
}
